package io.gitee.jinceon.pmd;

import net.sourceforge.pmd.*;
import net.sourceforge.pmd.renderers.HTMLRenderer;
import org.springframework.util.CollectionUtils;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CodePmdChecker {

    public void check() {
        System.out.println("                     _                    _             _                     _                     _    \n" +
                "                    | |                  | |           | |                   | |                   | |   \n" +
                "   ___    ___     __| |   ___       ___  | |_   _   _  | |   ___        ___  | |__     ___    ___  | | __\n" +
                "  / __|  / _ \\   / _` |  / _ \\     / __| | __| | | | | | |  / _ \\      / __| | '_ \\   / _ \\  / __| | |/ /\n" +
                " | (__  | (_) | | (_| | |  __/     \\__ \\ | |_  | |_| | | | |  __/     | (__  | | | | |  __/ | (__  |   < \n" +
                "  \\___|  \\___/   \\__,_|  \\___|     |___/  \\__|  \\__, | |_|  \\___|      \\___| |_| |_|  \\___|  \\___| |_|\\_\\\n" +
                "                                                 __/ |                                                   \n" +
                "                                                |___/                                                    ");
        String dir = getClass().getClassLoader().getResource("").getPath();
        String base = dir.substring(1,dir.indexOf("target/classes"));
        Path sourceRoot = Paths.get(base+"/src/main/java/");
        if(!sourceRoot.toFile().canRead()){
            //仅本地运行，打成jar了就不扫描了
            System.err.println(sourceRoot+"不存在或不可读，跳过代码检查============");
            return;
        }
        PMDConfiguration configuration = new PMDConfiguration();
        configuration.addInputPath(sourceRoot);
//        configuration.addRuleSet("rulesets/java/quickstart.xml");
        configuration.addRuleSet("rules/custom.xml");
        configuration.setReportFormat("textcolor");
        PmdAnalysis analysis = PmdAnalysis.create(configuration);
        Report report = analysis.performAnalysisAndCollectReport();
        List<RuleViolation> violations = report.getViolations();

        Map<RulePriority, List<RuleViolation>> grouped = violations.stream().collect(Collectors.groupingBy(ruleViolation -> ruleViolation.getRule().getPriority()));
        if(!CollectionUtils.isEmpty(grouped.get(RulePriority.HIGH))){
            System.err.println(grouped.get(RulePriority.HIGH));
            throw new RuntimeException("存在严重违反规范(priority=HIGH)的代码，请修改后再启动");
        }
    }

}